// frontend/src/services/robotConnection.js
class RobotConnection {
    constructor() {
        this.ws = null;
        this.deviceId = null;
        this.token = null;
    }

    async connect(deviceId, token) {
        this.deviceId = deviceId;
        this.token = token;

        // 首先验证设备可用性
        const deviceStatus = await this.checkDeviceStatus(deviceId);
        if (!deviceStatus.available) {
            throw new Error('Device not available');
        }

        // 建立WebSocket连接
        this.ws = new WebSocket(`ws://10.10.3.27:8081`);

        this.ws.onopen = () => {
            // 发送认证信息
            this.ws.send(JSON.stringify({
                type: 'auth',
                deviceId: this.deviceId,
                token: this.token
            }));
        };

        this.setupMessageHandlers();
    }

    async checkDeviceStatus(deviceId) {
        const response = await fetch(`http://10.10.3.27:3001/api/devices/${deviceId}/status`, {
            headers: {
                'Authorization': `Bearer ${this.token}`
            }
        });
        return response.json();
    }

    setupMessageHandlers() {
        this.ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            switch (data.type) {
                case 'robot_data':
                    this.handleRobotData(data);
                    break;
                case 'status_update':
                    this.handleStatusUpdate(data);
                    break;
                case 'error':
                    this.handleError(data);
                    break;
            }
        };
    }

    sendCommand(command) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
                type: 'command',
                deviceId: this.deviceId,
                data: command
            }));
        }
    }
}
